﻿Imports Co9320.Sekatyaku
Imports Co9320.NicoLiveService

Public Class MainWorkflow
    Inherits SequentialWorkflowActivity

    Private _Videos As Video()
    Public Property Videos As Video()
        Get
            Return _Videos
        End Get
        Set(ByVal value As Video())
            _Videos = value
        End Set
    End Property

    Private WithEvents _CommentServer As CommentServer
    Public Property CommentServer As CommentServer
        Get
            Return _CommentServer
        End Get
        Set(ByVal value As CommentServer)
            _CommentServer = value
        End Set
    End Property

    Private VideoIndex As Integer

    Public ReadOnly Property CurrentVideo As Video
        Get
            If Videos IsNot Nothing AndAlso VideoIndex < Videos.Length Then
                Return Videos(VideoIndex)
            Else
                Return Nothing
            End If
        End Get
    End Property

    Public ReadOnly Property CurrentDateTime As DateTime
        Get
            Return DateTime.Now
        End Get
    End Property
    Private _StartDateTime As DateTime
    Public Property StartDateTime As DateTime
        Get
            Return _StartDateTime
        End Get
        Set(ByVal value As DateTime)
            _StartDateTime = value
        End Set
    End Property

    Private _Continued As Boolean
    Public ReadOnly Property Continued As Boolean
        Get
            Return _Continued
        End Get
    End Property

    Private LatestVotingResult As String
    Private VoteResultShowingEvent As New ManualResetEvent(False)







    Private Sub _CommentServer_CommentReceived(ByVal sender As Object, ByVal e As Co9320.NicoLiveService.CommentEventArgs) Handles _CommentServer.CommentReceived
        If Not e.Comment.Text.StartsWith("/vote showresult") OrElse e.Comment.Premium <> 3 Then
            Exit Sub
        End If

        LatestVotingResult = e.Comment.Text
        VoteResultShowingEvent.Set()
    End Sub



    Private Sub codeActivity3_ExecuteCode(ByVal sender As System.Object, ByVal e As System.EventArgs)
        CommentServer.SendBroadcastComment("/play " & CurrentVideo.Id & " sub", 3)
        ShowHeader()
        If VideoIndex < Videos.Length - 1 Then
            CommentServer.SendBroadcastComment("/prepare " & Videos(VideoIndex + 1).Id)
        End If
        _Continued = True
        StartDateTime = Now

    End Sub
    Private Sub ShowHeader()

        Dim title = CurrentVideo.Title.Replace(vbCrLf, "")
        If title.Length > 40 Then
            title = title.Substring(0, 40)
        End If
        Dim desc = CurrentVideo.Description.Replace(vbCrLf, "")
        If desc.Length > 40 Then
            desc = desc.Substring(0, 40)
        End If

        title = System.Web.HttpUtility.HtmlDecode(title)
        desc = System.Web.HttpUtility.HtmlEncode(desc)

        Dim postDate = CurrentVideo.FirstRetrieveDateTime.ToString("yyyy-MM-dd HH:mm:ss")

        Dim perm = String.Format( _
            "/perm <font color=""#FF9900"">投稿日時:{0}</font><br>" & _
            "タイトル:{1}<br>" & _
            "<font color=""#C0C0C0"">{2}<font>", _
            postDate, _
            title, _
            desc)

        CommentServer.SendBroadcastComment(perm, "hidden", 3)


    End Sub

    Private Sub codeActivity1_ExecuteCode(ByVal sender As System.Object, ByVal e As System.EventArgs)
        For i = 5 To 1 Step -1
            CommentServer.SendBroadcastComment(String.Format("/perm 後 {0} 秒で、『延長アンケート』を開始いたします。", i), "hidden")
            Thread.Sleep(1000)
        Next

        CommentServer.SendBroadcastComment("/vote start 引き続きこの動画を視聴しますか？（過半数以上の支持で延長） はい いいえ", "hidden", 3)

    End Sub

    Private Sub codeActivity2_ExecuteCode(ByVal sender As System.Object, ByVal e As System.EventArgs)
        For i = 5 To 1 Step -1
            CommentServer.SendBroadcastComment(String.Format("/perm 『延長アンケート』（締め切りまで後 {0} 秒です。<br>引き続きこの動画を視聴しますか？（過半数以上の支持で延長）", i), "hidden")
            Thread.Sleep(1000)
        Next
        CommentServer.SendBroadcastComment("/vote showresult", "hidden", 3)
        CommentServer.SendBroadcastComment("/perm 『延長アンケート』（投票は締め切りました<br>引き続きこの動画を視聴しますか？（過半数以上の支持で延長）", "hidden", 3)

        VoteResultShowingEvent.WaitOne()
        VoteResultShowingEvent.Reset()

        Thread.Sleep(5000)
        CommentServer.SendBroadcastComment("/vote stop", "hidden", 3)

        Dim match = RegularExpressions.Regex.Match(LatestVotingResult, _
                                           "^/vote showresult per\s+(?<per1>\d+)\s+(?<per2>\d+)")
        If match.Success AndAlso _
            Convert.ToInt32(match.Groups("per1").Value) >= 500 Then
            _Continued = True
            ShowHeader()
        Else

            _Continued = False
            VideoIndex += 1
        End If


    End Sub

    Private Sub delayActivity3_InitializeTimeoutDuration(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim sec = CurrentVideo.Length.TotalSeconds - Now.Subtract(StartDateTime).TotalSeconds
        If sec < 0 Then
            sec = 0
        End If
        DirectCast(sender, DelayActivity).TimeoutDuration = New TimeSpan(0, 0, Convert.ToInt32(sec))

        VideoIndex += 1
        _Continued = False

    End Sub
End Class
